import { writeFile } from "fs/promises";
import { Action } from "@/mdesign-lib/mdesign-app.umd.js";
import { SavePathFor201Window } from "../customWindows/savePathFor201";
import { ApiCode } from "@/mdesign-lib/mdesign-app.umd.js";
import { modelTreeSelectWindow } from "@/mdesign-lib/mdesign-app.umd.js";
import { archService } from "@/mdesign-lib/mdesign-app.umd.js";
import { PropertyDataType } from "@/mdesign-lib/mdesign-app.umd.js";
import { actionManager } from "@/mdesign-lib/mdesign-app.umd.js";
import { localFile } from "@/mdesign-lib/mdesign-app.umd.js";
import { UploadFor201Window, CloseData, DownloadFor201Window } from "../customWindows/customFor201";
import { ActionKey } from "@/mdesign-lib/mdesign-app.umd.js";
import { StorageKey } from "@/util/Storage";

export class SavePathFor201Action extends Action {
  keyName = "SavePathFor201" as ActionKey;
  desc = "SavePathFor201";

  async run() {
    SavePathFor201Window.popup({ dir: this.getDir() }).then(({ dir, success }) => {
      if (success) {
        app.storage.set(StorageKey.archFor201SavePath, dir);
        app.$notify({ type: "success", title: "成功", message: "设置成功" });
      }
    });
  }

  getDir() {
    const documentPath = app.global.path.documents;
    const exportImageInfo = app.storage.get(StorageKey.archFor201SavePath) as string;
    return exportImageInfo || documentPath;
  }

  onSysMenuClick() {
    this.run();
  }
}

export class ExportFor201Action extends Action {
  keyName = "ExportFor201" as ActionKey;
  desc = "ExportFor201";

  async run() {
    const projectId = app.activeProject?.id;
    if (!projectId) throw new Error("无激活项目！");
    await modelTreeSelectWindow.popup(
      {
        loadMethod: "getPropertyTreeList",
        showNodeLabel: true,
        loadParams: JSON.stringify({
          row: {
            dataType: PropertyDataType.INSTANCE,
            moreBtnCondition: "72918954541382400",
            key: "",
            modelId: "72918954541382400",
            checkMethod: null,
            nullable: false
          },
          projectId
        }),
        checkable: false,
        delay: true,
        attrTip: "radio",
        title: "选择模型"
      },
      async res => {
        if (!res.success) return;
        const selectedId = res.selectedId as string;
        const dir = (actionManager.getAction("SavePathFor201") as SavePathFor201Action).getDir();
        console.log("dir", dir);
        const chooseFilePathResult = await localFile.chooseSaveFilePath({
          title: "选择导出位置",
          defaultPath: dir + "/Untitled.xml",
          filters: [
            {
              name: "xml",
              extensions: ["xml"]
            }
          ]
        });
        const filePath = chooseFilePathResult.filePath;
        if (chooseFilePathResult.canceled || !filePath) {
          modelTreeSelectWindow.abort();
          return;
        }
        const result = await archService.export201XML(projectId, selectedId as string);
        if (result.code === ApiCode.SUCCESS) {
          app.$notify({
            type: "success",
            title: "成功",
            message: "导出成功"
          });
        }
        modelTreeSelectWindow.done();
      }
    );
  }

  onSysMenuClick() {
    this.run();
  }
}

export class UploadFor201Action extends Action {
  keyName = "uploadFor201" as ActionKey;
  desc = "uploadFor201";

  async run() {
    const projectId = app.activeProject!.id;
    const projectFilePath = app.activeProject!.config.fullPath;
    const projectName = app.activeProject!.config.name + ".md3";
    await UploadFor201Window.popup({ projectId, projectFilePath, projectName }, async (res: CloseData) => {
      if (res.success) {
        app.$notify({ type: "success", title: "成功", message: "上传成功" });
        UploadFor201Window.done();
      } else {
        app.$notify({ type: "error", title: "失败", message: res.info });
      }
    });
  }

  onSysMenuClick() {
    this.run();
  }
}

export class DownloadFor201Action extends Action {
  keyName = "downloadFor201" as ActionKey;
  desc = "downloadFor201";

  async run() {
    const projectId = app.activeProject!.id;
    await DownloadFor201Window.popup({ projectId }, async (res: CloseData) => {
      if (res.success) {
        const info = res.info;
        const data = (await archService.download201Project(info.prjGuid, info.srcTool, info.nodeVersion)) as ArrayBuffer;
        if (!data) {
          app.$notify({ type: "error", title: "失败", message: "下载失败" });
          DownloadFor201Window.abort();
          return;
        }
        writeFile(info.filePath, new Uint8Array(data))
          .then(() => {
            DownloadFor201Window.abort();
            DownloadFor201Window.done();
            app.$notify({ type: "success", title: "成功", message: "下载成功" });
          })
          .catch(err => {
            DownloadFor201Window.abort();
            app.$notify({ type: "error", title: "失败", message: err.toString() });
          });
      }
    });
  }

  onSysMenuClick() {
    this.run();
  }
}

export class ExportZipFor201Action extends Action {
  keyName = "exportZipFor201" as ActionKey;
  desc = "exportZipFor201";

  async run() {
    const projectId = app.activeProject!.id;
    const projectFilePath = app.activeProject!.config.fullPath;
    const projectName = app.activeProject!.config.name + ".md3";
    await UploadFor201Window.popup({ projectId, projectFilePath, projectName, exportZip: true }, async (res: CloseData) => {
      if (res.success) {
        app.$notify({ type: "success", title: "成功", message: "成功" });
        UploadFor201Window.done();
      } else {
        app.$notify({ type: "error", title: "失败", message: res.info });
      }
    });
  }

  onSysMenuClick() {
    this.run();
  }
}
